import { Pool } from 'pg';
import { Logger } from './log4js';
import dbConfig from '../config/dataSource';
import ActionResult from './../common/ResponseResult';
const pgConfig = {
  ...dbConfig,
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
};
const pool = new Pool(pgConfig);
const logger = Logger;
const queryPgDatabases: any = async ({
  sql,
  params = [],
}: {
  sql: string;
  params: Array<string | number>;
}) => {
  let client: any = [];
  let result: any = [];
  logger.sql(`${sql},参数--->${JSON.stringify(params)}`);
  try {
    client = await pool.connect();
    result = await client.query(sql, params);
    client.release();
    return ActionResult.success({ data: result.rows, message: '查询成功' });
  } catch (error) {
    logger.error(`${error} ${sql},参数--->${JSON.stringify(params)}`);
    return ActionResult.fail({ data: [], message: '后端错误，请联系管理员' });
  }
};
const insertPgDatabases: any = async ({
  sql,
  params = [],
}: {
  sql: string;
  params: Array<string | number>;
}) => {
  let client: any = [];
  let result: any = [];
  logger.sql(`${sql},参数--->${JSON.stringify(params)}`);
  try {
    client = await pool.connect();
    result = await client.query({
      text: sql,
      values: params,
      rowMode: 'array',
    });
    client.release();
    return ActionResult.success({ data: result.rows, message: '新增成功' });
  } catch (error) {
    logger.error(`${error} ${sql},参数--->${JSON.stringify(params)}`);
    return ActionResult.fail({ data: [], message: '后端错误，请联系管理员' });
  }
};
const updatePgDatabases: any = async ({
  sql,
  params = [],
}: {
  sql: string;
  params: Array<string | number>;
}) => {
  let client: any = [];
  let result: any = [];
  logger.sql(`${sql},参数--->${JSON.stringify(params)}`);
  try {
    client = await pool.connect();
    result = await client.query({
      text: sql,
      values: params,
      rowMode: 'array',
    });
    client.release();
    return ActionResult.success({ data: result.rows, message: '新增成功' });
  } catch (error) {
    logger.error(`${error} ${sql},参数--->${JSON.stringify(params)}`);
    return ActionResult.fail({ data: [], message: '后端错误，请联系管理员' });
  }
};
const deletePgDatabases: any = async ({
  sql,
  params = [],
}: {
  sql: string;
  params: Array<string | number>;
}) => {
  let client: any = [];
  let result: any = [];
  logger.sql(`${sql},参数--->${JSON.stringify(params)}`);
  try {
    client = await pool.connect();
    result = await client.query({
      text: sql,
      values: params,
      rowMode: 'array',
    });
    client.release();
    return ActionResult.success({ data: result.rows, message: '新增成功' });
  } catch (error) {
    logger.error(`${error} ${sql},参数--->${JSON.stringify(params)}`);
    return ActionResult.fail({ data: [], message: '后端错误，请联系管理员' });
  }
};
export {
  queryPgDatabases,
  insertPgDatabases,
  updatePgDatabases,
  deletePgDatabases,
};
